package cn.leyaber.hrm.serviec.impl;

import cn.leyaber.hrm.Result.Result;
import cn.leyaber.hrm.Result.UpLoadResult;
import cn.leyaber.hrm.config.AliyunConfig;
import cn.leyaber.hrm.serviec.IFileUpLoadService;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;
@Service
public class FileUpLoadServiceImpl implements IFileUpLoadService {
    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private OSSClient ossClient;
    // 限制上传文件大小
    private static final Long MAX_SIZE = 1024L * 1024 * 5;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    public UpLoadResult upload(MultipartFile uploadFile) {
        // 校验图片格式
        boolean isLegal = false;
        for (String type : IMAGE_TYPE) {
            if (StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(), type)) {
                isLegal = true;
                break;
            }
        }
        UpLoadResult uploadResult = new UpLoadResult();
        if(MAX_SIZE < uploadFile.getSize()) {
            uploadResult.setStatus("文件大小不能超过5m");
            return uploadResult;
        }
        if (!isLegal) {
            uploadResult.setStatus("error");
            return uploadResult;
        }
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        try {
            ossClient.putObject(aliyunConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
            //上传失败
            uploadResult.setStatus("error");
            return uploadResult;
        }
        uploadResult.setStatus("done");
        uploadResult.setName(this.aliyunConfig.getUrlPrefix() + filePath);
        uploadResult.setUid(String.valueOf(System.currentTimeMillis()));
        return uploadResult;
    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "datas/" + dateTime.toString("yyyy")
                + "/" + dateTime.toString("MM") + "/"
                + dateTime.toString("dd") + "/" + UUID.randomUUID().toString() +
                "." + StringUtils.substringAfterLast(sourceFileName, ".");
    }
    @Override
    public Result download(String uid, HttpServletResponse response) {
        Result result = new Result();
        try {
            String bucketName = aliyunConfig.getBucketName();
            OSSObject ossObject = ossClient.getObject(bucketName, uid);
            int buffer = 1024 * 10;
            byte data[] = new byte[buffer];
            if (ossObject != null) {
                InputStream inputStream = ossObject.getObjectContent();
                // 文件名可以任意指定
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(uid, "UTF-8"));
                int read;
                while ((read = inputStream.read(data)) != -1) {
                    response.getOutputStream().write(data, 0, read);
                }
                response.getOutputStream().flush();
                response.getOutputStream().close();
                ossObject.close();
            }
            result.setCode(404);
            result.setMessage("文件不存在");
            return result;
        } catch (Exception e) {
            OSSException ee = (OSSException) e;
            e.printStackTrace();
            result.setCode(500);
            result.setMessage(e.getMessage());
            return result;
        }
    }
    @Override
    public Result delete(String uid) {
        Result result = new Result();
        try {
            String bucketName = aliyunConfig.getBucketName();
            ossClient.deleteObject(bucketName, uid);
            result.setCode(200);
            result.setMessage("success");
        } catch (Exception e) {
            e.printStackTrace();
            result.setCode(500);
            result.setMessage("fail");
        }
        return result;
    }
}
